<template>
    <div class=" bg-white sticky top-0 left-0 z-10">
        <ul ref="ulTarget" class=" relative flex  overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden">
            <!-- 滑块 -->
            <li ref="silderTarget" :style="silderStyle" class=" absolute h-[22px] bg-zinc-900 rounded-lg  duration-300">
            </li>
            <!-- 汉堡按钮 -->
            <li class=" fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white z-20 shadow-l-white"
                @click="onShowPopup">
                <my-svg-icon class="w-1.5 h-1.5" name="hamburger"></my-svg-icon>
            </li>
            <!-- items -->
            <li v-for="(item, index) in data" :key="item.id" :ref="setItemRef"
                class=" shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
                :class="{ 'text-zinc-100': currentCategoryIndex === index }" @click="onItemClick(item, index)">
                {{ item.name }}
            </li>
        </ul>

        <my-popup v-model="isVisable">
            <menu-vue :categorys="data" @onItemClick="onItemClick"></menu-vue>
        </my-popup>
    </div>
</template>

<script setup>
import { useScroll } from '@vueuse/core'
import { onBeforeUpdate, reactive, ref, watch } from 'vue-demi'
import menuVue from '@/views/main/components/menu/index.vue'
import alldata from '@/api/data'


defineProps({
    data: {
        type: Array,
        required: true
    }
})


// 滑块
const silderStyle = ref({
    transform: 'translateX(0px)',
    width: '60px'
})

// 选中 item 下标
const currentCategoryIndex = ref(0)

// 获取所有的 item 元素
let itemRefs = []
const setItemRef = el => {
    if (el) {
        itemRefs.push(el)
    }
}

// 数据改变之后，dom变化之前
onBeforeUpdate(() => {
    itemRefs = []
})
// 获取ul元素
const ulTarget = ref(null)
// 通过 vueuse => usescroll 获取响应的 scroll 滚动距离
const { x: ulScrollLeft } = useScroll(ulTarget)

// wacth 监听
watch(currentCategoryIndex, (val) => {
    const { left, width } = itemRefs[val].getBoundingClientRect()
    silderStyle.value = {
        // 滑块的位置= ul 横向滚动的位置 + 当前元素的left -ul 的paddidng
        transform: `translateX(${ulScrollLeft.value + left - 10}px)`,
        width: width + 'px',
    }
})
// item 点击事件
const onItemClick = (item, index) => {

    currentCategoryIndex.value = index
    isVisable.value = false
    let alldataList = alldata[0].data
    alldataList.map(val => {

        if (val.id === item.id) {
            console.log(val)
            return item
        }
    })

}

// 控制弹窗flag
const isVisable = ref(false)
const onShowPopup = () => {
    isVisable.value = true

}
</script> 

<style lang="scss" scoped>

</style>